<script lang="ts">
  import type { EditorView } from "@codemirror/view";
  import { setLineStatuses } from "@rilldata/web-common/components/editor/line-status";
  import type { LineStatus } from "@rilldata/web-common/components/editor/line-status/state";
  import { metricsPlusSQL } from "@rilldata/web-common/components/editor/presets/yamlWithJsonAndSql";
  import { clearMostRecentExploreState } from "@rilldata/web-common/features/dashboards/state-managers/loaders/most-recent-explore-state";
  import { metricsExplorerStore } from "@rilldata/web-common/features/dashboards/stores/dashboard-stores";
  import { clearExploreSessionStore } from "@rilldata/web-common/features/dashboards/state-managers/loaders/explore-web-view-store";
  import Editor from "@rilldata/web-common/features/editor/Editor.svelte";
  import { FileArtifact } from "@rilldata/web-common/features/entity-management/file-artifact";
  import { fileArtifacts } from "@rilldata/web-common/features/entity-management/file-artifacts";
  import { ResourceKind } from "@rilldata/web-common/features/entity-management/resource-selectors";
  import WorkspaceEditorContainer from "@rilldata/web-common/layout/workspace/WorkspaceEditorContainer.svelte";
  import { yamlSchema } from "codemirror-json-schema/yaml";
  import type { JSONSchema7 } from "json-schema";
  import { createPlaceholder } from "./create-placeholder";
  import metricsSchema from "./metrics-schema.json";

  export let filePath: string;
  export let metricsViewName: string;
  export let errors: LineStatus[];
  export let fileArtifact: FileArtifact;
  export let autoSave: boolean;

  let editor: EditorView;
  const metricsJsonSchema = metricsSchema as JSONSchema7;

  /** create placeholder codemirror extension and set the inner svelte component
   * generated by the createPlaceholder callback.
   */
  $: placeholderElements = createPlaceholder(filePath, metricsViewName);
  $: if (editor) placeholderElements.component.setEditorView(editor);

  /** If the errors change, run the following transaction. */
  $: if (editor) setLineStatuses(errors, editor);

  /** display the main error (the first in this array) at the bottom */
  $: mainError = errors?.at(0);
</script>

<WorkspaceEditorContainer error={mainError}>
  <Editor
    bind:autoSave
    bind:editor
    onSave={(content) => {
      // Remove the explorer entity so that everything is reset to defaults next time user navigates to it
      metricsExplorerStore.remove(metricsViewName);
      // Reset local persisted dashboard state for the metrics view
      clearExploreSessionStore(metricsViewName, undefined);
      clearMostRecentExploreState(metricsViewName, undefined);

      // Reset local persisted explore state derived from this metrics view
      fileArtifacts
        .getNamesForKind(ResourceKind.Explore)
        .forEach((resourceName) => {
          clearExploreSessionStore(resourceName, undefined);
          clearMostRecentExploreState(resourceName, undefined);
        });
      if (!content?.length) {
        setLineStatuses([], editor);
      }
    }}
    {fileArtifact}
    extensions={[
      metricsPlusSQL,
      placeholderElements.extension,
      yamlSchema(metricsJsonSchema),
    ]}
  />
</WorkspaceEditorContainer>
